package org.example.leetcode.interview.linkedlist;

import org.example.util.IO;
import org.example.util.ListNode;

public class LC0160 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode currA = headA;
        int lengthA = 0;
        ListNode currB = headB;
        int lengthB = 0;

        while (currA != null) {
            ++lengthA;
            currA = currA.next;
        }

        while (currB != null) {
            ++lengthB;
            currB = currB.next;
        }

        int inter = Math.abs(lengthA - lengthB);
        currA = headA;
        currB = headB;

        while (inter-- > 0) {
            if (lengthA > lengthB) {
                currA = currA.next;
            } else {
                currB = currB.next;
            }
        }

        while (currA != null) {
            if (currA == currB) {
                return currA;
            }

            currA = currA.next;
            currB = currB.next;
        }

        return null;
    }

    public static void main(String[] args) {
        LC0160 solu = new LC0160();
        System.out.println(solu.getIntersectionNode(IO.intLinkedList("[5,6,1,8,4,5]"), IO.intLinkedList("[4,1,8,4,5]")));
    }
}
